<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <!-- <el-form-item label="部门ID" prop="deptId">
        <el-input
          v-model="queryParams.deptId"
          placeholder="请输入部门ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <el-form-item label="工序号" prop="processNo">
        <el-input v-model="queryParams.processNo" placeholder="请输入工序号" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="工位号" prop="stationNo">
        <el-input v-model="queryParams.stationNo" placeholder="请输入工位号" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="工位名称" prop="stationName">
        <el-input v-model="queryParams.stationName" placeholder="请输入工位名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="工位类型" prop="stationType">
        <el-select v-model="queryParams.stationType" placeholder="请选择工位类型" clearable>
          <el-option v-for="dict in stationTypes" :key="dict.dictValue" :label="dict.dictLabel"
            :value="dict.dictValue" />
        </el-select>
      </el-form-item>
      <el-form-item label="工位状态" prop="stationState">
        <el-select v-model="queryParams.stationState" placeholder="请选择工位状态" clearable>
          <el-option v-for="dict in stationStates" :key="dict.dictValue" :label="dict.dictLabel"
            :value="dict.dictValue" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['zndd:station:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['zndd:station:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['zndd:station:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['zndd:station:export']">导出</el-button>
      </el-col>
      <el-col :span="1.5">
            <el-button
              type="info"
              plain
              icon="el-icon-upload2"
              size="mini"
              @click="handleImport"
              v-hasPermi="['zndd:station:import']"
            >导入</el-button>
          </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="stationList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column type="index" label="序号" />
      <!-- <el-table-column label="主键" align="center" prop="id" /> -->
      <!-- <el-table-column label="部门ID" align="center" prop="deptId" /> -->
      <el-table-column label="工序号" align="center" prop="processNo" />
      <el-table-column label="工位号" align="center" prop="stationNo" />
      <el-table-column label="工位名称" align="center" prop="stationName" />
      <el-table-column label="工位类型" align="center" prop="stationType" :formatter="stationTypeFomatter"/>
      <el-table-column label="工位状态" align="center" prop="stationState" :formatter="stationStateFomatter"/>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作"  width="300" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button v-if="scope.row.stationType == 1" size="mini" type="text" icon="el-icon-s-platform" @click="processdeviceBt(scope.row)"
            >查看绑定机器</el-button>
            <el-button v-if="scope.row.stationType == 2" size="mini" type="text" icon="el-icon-user" @click="processdetailsBt(scope.row)"
            >查看关联人员</el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['zndd:station:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['zndd:station:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改工位信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <!-- <el-form-item label="部门ID" prop="deptId">
          <el-input v-model="form.deptId" placeholder="请输入部门ID" />
        </el-form-item> -->
        <el-form-item label="工序号" prop="processNo">
          <el-input v-model="form.processNo" placeholder="请输入工序号" />
        </el-form-item>
        <el-form-item label="工位号" prop="stationNo">
          <el-input v-model="form.stationNo" placeholder="请输入工位号" />
        </el-form-item>
        <el-form-item label="工位名称" prop="stationName">
          <el-input v-model="form.stationName" placeholder="请输入工位名称" />
        </el-form-item>
        <el-form-item label="工位类型" prop="stationType">
          <el-select v-model="form.stationType" placeholder="请选择工位类型">
            <el-option v-for="dict in stationTypes" :key="dict.dictValue" :label="dict.dictLabel" :value="dict.dictValue" />
          </el-select>
        </el-form-item>
        <el-form-item label="工位状态" prop="stationState" v-if="this.form.stationType == 2">
          <el-select v-model="form.stationState" placeholder="请选择工位状态">
            <el-option v-for="dict in stationStates" :key="dict.dictValue" :label="dict.dictLabel" :value="dict.dictValue" />
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="deviceFormTitle" :visible.sync="deviceFormOpen" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="设备编号" prop="deviceNo">
          <el-input v-model="deviceForm.deviceNo" :disabled="true" />
        </el-form-item>
        <el-form-item label="设备名称" prop="deviceName">
          <el-input v-model="deviceForm.deviceName" :disabled="true" />
        </el-form-item>
        <el-form-item label="设备型号" prop="deviceModel">
          <el-input v-model="deviceForm.deviceModel" :disabled="true"/>
        </el-form-item>
        <el-form-item label="设备规格" prop="deviceSpecification" disabled="true">
          <el-input v-model="deviceForm.deviceSpecification" :disabled="true" />
        </el-form-item>
        <el-form-item label="设备类型" prop="deviceType">
          <el-input v-model="deviceForm.deviceType" :disabled="true" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="deviceForm.remark" :disabled="true"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="warning" @click="delectDevice">解除绑定</el-button>
      </div>
    </el-dialog>

    <!-- 工位导入对话框 -->
    <el-dialog style="align-content: center;" :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <div class="el-upload__tip" slot="tip">
            <el-checkbox v-model="upload.updateSupport" /> 是否更新已经存在的工位数据
          </div>
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载模板</el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 工位绑定机器界面对话框 -->
    <el-dialog :title="processdeviceTitle" :visible.sync="processdeviceFlag" width="1000px" append-to-body>
      <div>
        <process-device ref="processdevice" @closeProcessdeviceFlag="closeProcessdeviceFlag"></process-device>
      </div>
    </el-dialog>
    <!-- 工位绑定机器界面对话框 -->
    <el-dialog :title="processdetailsTitle" :visible.sync="processdetailsFlag" width="1000px" append-to-body>
      <div>
        <process-details ref="processdetails"></process-details>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listStation, getStation, delStation, addStation, updateStation } from "@/api/zndd/process/station";
import { getToken } from "@/utils/auth";
import { getDicts } from "@/api/system/dict/data";
import { selectDeviceByStation,getIdByStation,delProcessdevice} from "@/api/zndd/process/processdevice";
import Processdevice from "../processdevice/index.vue";
import Processdetails from "../processdetails/index.vue";

export default {
  name: "Station",
  components: {
    'process-device': Processdevice,
    'process-details':Processdetails,
  },
  data() {
    return {
      //人员绑定机器界面标题
      processdetailsTitle: "",
      //人员绑定机器界面是否显示
      processdetailsFlag: false,
      //设备详情标题
      deviceFormTitle:"",
      //设备详情界面是否显示
      deviceFormOpen: false,
      //设备详情界面内容
      deviceForm:{
        deviceNo: null,
        deviceName: null,
        deviceType:null,
        deviceModel: null,
        deviceSpecification: null,
        deviceStatus: null,
      },
      //工位绑定机器界面标题
      processdeviceTitle: "",
      //工位绑定机器界面是否显示
      processdeviceFlag: false,
      //工位状态列表
      stationStates:[],
      //工位类型列表
      stationTypes:[],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 工位信息表格数据
      stationList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        deptId: null,
        processNo: null,
        stationNo: null,
        stationName: null,
        stationType: null,
        stationState: null
      },
      // 表单参数
      form: {},
      // 工位导入参数
      upload: {
        // 是否显示弹出层（工位导入）
        open: false,
        // 弹出层标题（工位导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的工位数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/zndd/station/importData"
      },
      // 表单校验
      rules: {
        processNo: [
          { required: true, message: "工序号不能为空", trigger: "blur" }
        ],
        stationNo: [
          { required: true, message: "工位号不能为空", trigger: "blur" }
        ],
        stationName: [
          { required: true, message: "工位名称不能为空", trigger: "blur" }
        ],
        stationType: [
          { required: true, message: "工位类型不能为空", trigger: "blur" }
        ],
        stationState: [
          { required: true, message: "工位状态不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    //获取字典表中工位状态
    this.getDicts("station_state").then(response => {
      this.stationStates = response.data;
    });
    //获取字典表中工位类型
    this.getDicts("zndd_process_type").then(response => {
      this.stationTypes = response.data;
    });
    this.getList();
  },
  methods: {
    processdetailsBt(row){
      this.processdetailsTitle = row.stationName+"的绑定人员查看界面";
      this.$nextTick(() => {
        this.$refs.processdetails.pdMethods(row);
      })
      this.processdetailsFlag = true;
    },
    //工位绑定机器界面或设备详情界面
    processdeviceBt(row) {
      this.deviceForm={
        deviceNo: null,
        deviceName: null,
        deviceType:null,
        deviceModel: null,
        deviceSpecification: null,
        deviceStatus: null,
      };
      var flag = false;
      selectDeviceByStation(row).then(response => {
        if(response.id != null){
          this.deviceForm = response;
          flag = true;
        }
        if(flag){
          this.deviceFormTitle = row.stationName+"的绑定设备查看界面";
          this.deviceFormOpen = true;
        }else{
          this.processdeviceTitle = row.stationName+"的绑定设备界面";
          this.$nextTick(() => {
            this.$refs.processdevice.pdMethods(row.id);
          })
          this.processdeviceFlag = true;
        }
      });
    },
    //关闭机器绑定工位界面
    closeProcessdeviceFlag(){
      this.processdeviceFlag = false;
    },
    //解除机器绑定
    delectDevice(){
      getIdByStation(this.deviceForm).then(response => {
        console.log(response)
        this.$modal.confirm('是否确认解除绑定？').then(function() {
          return delProcessdevice(response.rows[0].id);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("解除绑定成功");
          this.deviceFormOpen = false;
        }).catch(() => {
          this.deviceFormOpen = false;
        });
      })
    },
    //格式化工位状态
    stationStateFomatter(row, column) {
      var ss = null;
      this.stationStates.forEach(stationState => {
        if (stationState.dictValue == row.stationState) {
          ss = stationState;
        }
      });
      if (ss == null) {
        return "";
      } else {
        return ss.dictLabel;
      }
    },
    //格式化工位类型
    stationTypeFomatter(row, column) {
      var st = null;
      this.stationTypes.forEach(stationType => {
        if (stationType.dictValue == row.stationType) {
          st = stationType;
        }
      });
      if (st == null) {
        return "";
      } else {
        return st.dictLabel;
      }
    },
    /** 查询工位信息列表 */
    getList() {
      this.loading = true;
      listStation(this.queryParams).then(response => {
        this.stationList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        deptId: null,
        processNo: null,
        stationNo: null,
        stationName: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加工位信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getStation(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改工位信息";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateStation(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addStation(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除选中的工位信息？').then(function () {
        return delStation(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('zndd/station/export', {
        ...this.queryParams
      }, `工位信息_${new Date().getTime()}.xlsx`)
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "工位导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download('zndd/station/importTemplate', {
      }, `工位导入信息_${new Date().getTime()}.xlsx`)
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    }
  }
};
</script>
